package com.lego.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lego.bean.Reviews;
import com.lego.bean.User;
import com.lego.dao.OrdersDao;
import com.lego.dao.impl.OrdersDaoImpl;
import com.lego.service.OrdersService;
import com.lego.service.ReviewsService;
import com.lego.service.impl.OrdersServiceImpl;
import com.lego.service.impl.ReviewsServiceImpl;

@WebServlet("/sendReview.do")
public class SendReviewServlet extends HttpServlet{
	ReviewsService rs = new ReviewsServiceImpl();
	OrdersDao od = new OrdersDaoImpl();
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String rewContext = request.getParameter("rewContext");
		String orderIdStr = request.getParameter("orderId");
		int orderId = 0;
		try {
			orderId = Integer.parseInt(orderIdStr);
		} catch (Exception e) {
			System.out.println("查询所有的评论！");
		}
		Reviews reviews = rs.selectCmt(orderId, rewContext);
		System.out.println(reviews == null);
		//如果不存在，那就创建一条评论，，
		if(reviews == null) {
			//从session变量里面取出loginUser的userId
			Object u = session.getAttribute("loginUser");
			User loginUser = null;
	 	   	if (u != null) {
	 	   		try {
	 	            loginUser = (User) u; // 强制类型转换
	 	            // 现在可以使用user对象
	 	        } catch (ClassCastException e) {
	 	            // 处理类型转换失败的情况
	 	            System.err.println("用户未登录");
	 	        }
	 	    }
			int userId = loginUser.getUserId();
			int goodsId = od.selectGoodsId(orderId);
			//通过orderId查出goodsId
			int row = rs.insertCmt(orderId, rewContext, userId, goodsId);
			if(row == 1) {
				//添加一条评论语句，添加完成评论语句，将order表的对应orderId的状态从待评论更新为已完成
				od.changeStatus(orderId);
			}
		}else {
			//通过orderId查询reviews表评论是否存在，如果存在那就直接更新评论，
			System.out.println(rewContext+"+"+orderId);
			rs.upDateCmt(rewContext, orderId);
			od.changeStatus(orderId);
		}
	}
}
